
package com.yimixian.app.fragment;

import com.ta.utdid2.android.utils.StringUtils;
import com.yimixian.app.EventBusDomain.OrderListPointTab;
import com.yimixian.app.R;
import com.yimixian.app.activity.YMXMainActivity;
import com.yimixian.app.adapter.OrdersListViewAdapter;
import com.yimixian.app.common.CacheKeys;
import com.yimixian.app.common.Constants;
import com.yimixian.app.data.DataManager;
import com.yimixian.app.model.Order;
import com.yimixian.app.rest.YmxDataService;
import com.yimixian.app.rest.api.ClearRedPointAPI;
import com.yimixian.app.rest.api.OrdersListAPI;
import com.yimixian.app.ui.BaseHttpFragment;
import com.yimixian.app.util.ObservableUtils;
import com.yimixian.app.util.SharedPreferencesHelper;
import com.ymx.sdk.widget.ListViewLoadMore.AutoPullToRefreshListView;
import com.ymx.sdk.widget.ListViewLoadMore.AutoPullToRefreshListViewBase;
import com.ymx.sdk.widget.PullToRefreshView.PullToRefreshBase;

import de.greenrobot.event.EventBus;

import org.json.JSONObject;

import rx.Subscription;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import butterknife.ButterKnife;
import butterknife.InjectView;

import java.util.ArrayList;
import java.util.List;

public class OrderFragment extends BaseHttpFragment implements
        AutoPullToRefreshListView.OnLoadMoreListener,
        PullToRefreshBase.OnRefreshListener2<ListView> {

    @InjectView(R.id.orders_list)
    AutoPullToRefreshListView mOrdersListView;
    @InjectView(R.id.iv_no_login)
    ImageView mIvNoLogin;
    @InjectView(R.id.tv_login)
    TextView mTvLogin;
    @InjectView(R.id.rl_login)
    RelativeLayout mRlLogin;
    @InjectView(R.id.tv_button_txt)
    TextView mTvButtonTxt;

    private YmxDataService mYmxDataService;
    private DataManager mDataManager;
    private ArrayList<Order> mOrders;
    // private ProgressDialogFragment mProgressDialog;
     private boolean isLoading = false;
    private boolean is_commit = false;
    private View mNoData;
    private OrdersListAPI mOrdersListAPI;
    private ClearRedPointAPI mClearRedPointAPI;
    private boolean showDialog = true;
    OrdersListViewAdapter adapter;
    private int LISTSTATUS = Constants.Action.PULLDOWAN;
    private boolean isClearRedPoint = true;

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.arg1 == 0) {
                is_commit = true;
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        isClearRedPoint = true;
        mYmxDataService = YmxDataService.getInstance();
        mDataManager = DataManager.getInstance();
        View view = inflater.inflate(R.layout.show_orders_activity, null);
        mNoData = view.findViewById(R.id.order_no_data);
        ButterKnife.inject(this, view);
        mOrdersListView.setOnLoadMoreListener(this);
        initNodataView();
        adapter = new OrdersListViewAdapter(
                getActivity());
        adapter.setHandler(mHandler);
        if (mOrders == null)
            mOrders = new ArrayList<>();
        adapter.setList(mOrders);
        mOrdersListView.setAdapter(adapter);
        mOrdersListView.setOnRefreshListener(this);
        fetchData(true, mOrdersListAPI.ORDER_LIST);
        mOrdersListView.addFrontView(true);
        return view;
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mOrdersListView != null) {
            mOrdersListView.onRefreshComplete();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (SharedPreferencesHelper.getBoolean(Constants.PAY_SUCCESS)) {
            SharedPreferencesHelper.commitBoolean(Constants.PAY_SUCCESS, false);
            showDialog = true;
            fetchData(true, mOrdersListAPI.ORDER_LIST);
        }
        if (is_commit) {
            showDialog = true;
            fetchData(true, mOrdersListAPI.ORDER_LIST);
            is_commit = false;
        }
    }

    @Override
    public void onDetach() {
        hideDialog();
        // UiUtils.dismiss(mProgressDialog);
        super.onDetach();
    }

    @Override
    public void onLoadMore() {
        LISTSTATUS = Constants.Action.PUSHUP;
        showDialog = false;
        if (checkNetWorkState())
            fetchData(true, mOrdersListAPI.ORDER_LIST);
        else
            mOrdersListView.onLoadMoreComplete();
    }

    public void initNodataView() {
        mIvNoLogin.setImageResource(R.drawable.ic_no_order_data);
        mTvLogin.setText(getString(R.string.order_no_data_tips));
        mTvButtonTxt.setText(getString(R.string.go_home));
        mRlLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getActivity() instanceof YMXMainActivity) {
                    ((YMXMainActivity) getActivity()).setHomeTab();
                }
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void initRequestAPI(String requestKeys) {
        if (StringUtils.isEmpty(mDataManager
                .<String> get(CacheKeys.TOKEN)))
            return;

        // 清除小红点
        if (requestKeys != null && requestKeys.equals(ClearRedPointAPI.CLEARURL)) {
            if (isClearRedPoint) {
                mClearRedPointAPI = new ClearRedPointAPI(mDataManager
                        .<String>get(CacheKeys.TOKEN), Constants.RedPointType.ORDER, this);
            }
        } else {// 列表数据
            if (LISTSTATUS == Constants.Action.PULLDOWAN) {
                mOrdersListAPI = new OrdersListAPI(0, Constants.PAGE_SIZE, mDataManager
                        .<String>get(CacheKeys.TOKEN), this);
            } else {
                int last_id;
                if (mOrders.size() > 0) {
                    last_id = mOrders.get(mOrders.size() - 1).id;
                } else {
                    return;
                }
                mOrdersListAPI = new OrdersListAPI(last_id, Constants.PAGE_SIZE, mDataManager
                        .<String>get(CacheKeys.TOKEN), this);
            }
            if (isLoading) {
                return;
            }
            isLoading = true;
            if (showDialog) {
                showDialog("载入订单...", false);
                // mProgressDialog = UiUtils.showProgressDialog(getActivity(),
                // "载入订单...", true);
            }
        }
    }

    @Override
    public void fetchDataFromNetwork(String key) {
        initRequestAPI(key);
        if (key != null && mOrdersListAPI != null && key.equals(OrdersListAPI.ORDER_LIST)) {
            mOrdersListAPI.getOrdersList();
        }
        if (key != null && mClearRedPointAPI != null && key.equals(ClearRedPointAPI.CLEARURL)) {
            mClearRedPointAPI.toClearRedPoint();
        }
    }

    @Override
    public void onHttpSuccess(String url, JSONObject responseJson) {
        hideDialog();
        // 刷新出列表数据
        if (url.contains(OrdersListAPI.ORDER_LIST) && mOrdersListAPI != null) {

            // 清除订单红色按钮
            if (isClearRedPoint) {
                EventBus.getDefault().post(new OrderListPointTab(0, Constants.RedPointType.ORDER, false));
                fetchData(true, mClearRedPointAPI.CLEARURL);
            }
            isClearRedPoint = false;
            List<Order> orders = mOrdersListAPI.parseJson(responseJson);
            // 下拉刷新
            if (mOrdersListAPI.back_last_id == 0) {
                if (mOrdersListView == null) {
                    return;
                }
                mOrdersListView.onRefreshComplete();
                if (orders != null && orders.size() > 0) {
                    mNoData.setVisibility(View.GONE);
                    mOrdersListView.setVisibility(View.VISIBLE);
                } else {
                    mNoData.setVisibility(View.VISIBLE);
                    mOrdersListView.setVisibility(View.GONE);
                }
                mOrders.clear();
                mOrders.addAll(orders);
            } else {
                mOrders.addAll(orders);
                mOrdersListView.onLoadMoreComplete();
                if (orders.size() < Constants.PAGE_SIZE) {
                    mOrdersListView.setIsEnable(false);
                }
            }
            adapter.setList(mOrders);
            isLoading = false;
            // UiUtils.dismiss(mProgressDialog);
            mDataManager.put(CacheKeys.ORDERS, mOrders);
        }
        // 清除小红点
        if (url.contains(ClearRedPointAPI.CLEARURL)) {
            isClearRedPoint = false;
        }
    }

    @Override
    public void OnHttpFailure(String url, String errorMessage, boolean errorFromUs) {
        // UiUtils.dismiss(mProgressDialog);
        hideDialog();
        mOrdersListView.onLoadMoreComplete();
        mOrdersListView.onRefreshComplete();
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        mOrdersListView.setIsEnable(true);
        showDialog = false;
        LISTSTATUS = Constants.Action.PULLDOWAN;
        if (checkNetWorkState())
            fetchData(true, mOrdersListAPI.ORDER_LIST);
        else
            mOrdersListView.onRefreshComplete();

    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {

    }
}
